package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.pojo.Orders;
import com.itheima.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功");

    }

    @GetMapping("/userPage")
    public R<Page> page(int page,int pageSize){
        Long currentId = BaseContext.getCurrentId();
        Page<Orders> pageInfo = new Page<>(page , pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,currentId);
        ordersService.page(pageInfo,qw);

        return R.success(pageInfo);
    }

    @GetMapping("/page")
    public R<Page> page2(int page,int pageSize){
        Page<Orders> pageInfo = new Page<>(page , pageSize);
        ordersService.page(pageInfo);

        Page<OrdersDto> pageDto  = new Page<>();
        BeanUtils.copyProperties(pageInfo,pageDto,"records");

        List<OrdersDto> list = pageInfo.getRecords().stream().map((item) -> {

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());

        pageDto.setRecords(list);

        return R.success(pageInfo);
    }


    @PutMapping
    public R<String> update(@RequestBody Orders order){

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getNumber,order.getId());

        Orders orders = ordersService.getOne(qw);
        orders.setStatus(order.getStatus());
        ordersService.updateById(orders);

        return R.success("修改成功");
    }
}
